<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
             <div>
              任务名称：<el-input placeholder="请输入内容" v-model="selectForm.eventName" clearable class="dzy-custom-input"></el-input>
            </div>
            <!--<div>
              发生地点：<el-input placeholder="请输入内容" v-model="selectForm.happenAddress" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              主要当事人姓名：<el-input placeholder="请输入内容" v-model="selectForm.partyName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>-->
            <div>选择时间：
              <el-date-picker
                  v-model="selectForm.createTime"
                  type="datetime"
                  value-format="timestamp"
                  default-time="12:00:00"
                  placeholder="选择到达时间">
              </el-date-picker>&nbsp;至
              <el-date-picker
                  v-model="selectForm.endTime"
                  type="datetime"
                  value-format="timestamp"
                  default-time="12:00:00"
                  placeholder="选择结束时间">
              </el-date-picker>&nbsp;
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="historicPageData"
            :table-columns="historicColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows"
            v-on:checkTimerShaftHandle="checkTimerShaftHandle"
            v-on:checkFlowHandle="checkFlowHandle">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="isCheckFlowDialogShow" :before-close="cancel" class="custom-dialog-style-imgDialog">
            <div id="imgContainer">
              <img :src="isImgData" style="width: 100%;" />
            </div>
          </el-dialog>
          <el-dialog title="任务流转情况" :visible.sync="isTimerShaftDialogShow" :before-close="cancel">
            <div class="block custom-timerShaftDialog-style">
              <div style="height: 140px;border: 1px solid #ccc;border-radius: 4px; margin-bottom: 14px;margin-left: 28px;padding: 0 20px 3px 20px;clear: fixed">
                <div class="custom-content-left">
                  <p>{{formData.eventSource}}--{{formData.reporterName}}</p>
                  <p>{{formData.reportDate | formatDate}}</p>
                  <p>{{formData.description}}</p>
                </div>
                <template v-if="formData.photoArr&&formData.photoArr.length>0">
                  <div class="custom-img-right">
                  <div v-for='(item,index) in formData.photoArr' class="timeTop-right" :key="index">
                    <img  :src="baseUrl+'/image/'+item" alt="" />
                  </div>
                  </div>
                </template>
              </div>
              <div class="custom-timerStatusContainer-style">{{status}}</div>
              <el-timeline pending>
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :timestamp="activity.startTime | formatDate"
                  placement="top">
                  <el-card class="cardWapper">
                    <div class="cardLeft">
                      <p>任务名称：{{activity.taskName}}</p>
                      <p>处理人：{{activity.assigneeName}}</p>
                      <p v-for="(com,index) in activity.comments" :key="index">处理记录：{{com}}</p>
                      <div v-if="index === activities.length - 1">
                        <p v-if="activity.endTime === 0">状态：<span style="color:red;font-size:16px;">办理中...</span></p>
                        <p v-else>状态：<span style="color:red;font-size:16px;">已完结</span></p>
                      </div>
                    </div>
                    <div class="cardRight">
                      <template v-if="activity.photoArr&&activity.photoArr.length>0">
                        <div v-for='(item,index) in activity.photoArr' class="timeTop-right imgWapper" :key="index">
                          <img  :src="baseUrl+'/image/'+item" alt="" />
                        </div>
                      </template>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-dialog>
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            class="custom-dialog_style_twoLine"
            :before-close="cancel"
            :close-on-click-modal="false">
            <el-form :model="formData" label-width="50%">
              <el-form-item label="上报人：" label-width="30%">
                <el-input v-model="formData.reporterName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="上报人电话：" label-width="30%">
                <el-input v-model="formData.reporterContact" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="上报时间：" label-width="30%">
                <el-date-picker
                  v-model="formData.reportDate"
                  value-format="timestamp"
                  placeholder="选择日期时间"
                  :picker-options="dataPickerBeforeTodayOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="事件分类：" label-width="30%" style="margin-bottom: 22px">
                <div class="block">
                  <el-select filterable v-model="formData.eventCategory" placeholder="请选择">
                    <el-option v-for="(item,index) in eventCategoryOption"
                      :key="index"
                      :value="item.id"
                      :label="item.valueName"></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="经度：" label-width="30%">
                <el-input v-model="formData.longitude" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="纬度：" label-width="30%">
                <el-input v-model="formData.latitude" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="发生地点：" label-width="30%">
                <el-input v-model="formData.happenAddress" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="街道/社区/网格：" label-width="30%">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="options"
                    filterable
                    clearable
                    :props="gridIdProps"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="事件描述：" label-width="30%" class="custom-textarea-container">
                <el-input type="textarea" v-model="formData.description"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="30%" class="custom-textarea-container">
              </el-form-item>
              <el-form-item label="图片：" class="custom-img-container" style="width:100%">
                <app-upload ref="appUpload" v-model="formData.photoArr" ></app-upload>
              </el-form-item>
              <el-form-item label="" label-width="30%" class="custom-textarea-container">
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppUpload from '@/components/AppMultiUpload'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import config from '@/config/index'
import {getAllRegion} from '@/utils/region'
import {getToken} from '@/utils/LocalDataUtil'
import {getEventCategory} from '@/data/DictData'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getHistoricTasks, findEventDetail, getTaskPhotoUrl, getTaskTimer} from '@/http/EventApi'
export default {
  data () {
    return {
      status: '',
      isImgData: '',
      baseUrl: config.serverUrl(),
      dialogFormVisible: false,
      treeData: [],
      historicPageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      historicColumns: [
        { prop: 'taskName', label: '任务名称', width: '150' },
        { prop: 'desc', label: '事件描述', width: '250' },
        { prop: 'procsName', label: '所属流程', width: '130' },
        { prop: 'createTime', label: '任务到达时间', formatter: this.dateFormatter, width: '120' },
        { prop: 'endTime', label: '任务结束时间', formatter: this.dateFormatter, width: '120' }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      options: [],
      selectForm: {
        offset: 0
      },
      formData: {},
      isCheckFlowDialogShow: false,
      isTimerShaftDialogShow: false,
      activities: [],
      timeLineStatus: '',
      gridIdProps: {
        value: 'id',
        label: 'name'
      },
      eventCategoryOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    AppUpload
  },
  mounted () {
    this.getTreeData()
    this.getTableData()
  },
  filters: {
    formatDate: function (value) {
      let date = new Date(value)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    }
  },
  methods: {
    setUri (ip) {
      let token = getToken()
      let path = config.serverUrl
      return path + ip + '?token=' + token
    },
    dateFormatter (row, column) {
      let prop = column.property
      let resTime = row[prop]
      return this.$moment(resTime).format('YYYY-MM-DD')
    },
    // 查看任务跟踪图
    checkFlowHandle (data) {
      if (data && data.data) {
        let getData = data.data[data.index]
        let path = ''
        if (getData.procsInsId) {
          path = getTaskPhotoUrl(true) + getData.procsInsId
        } else {
          path = getTaskPhotoUrl(false) + getData.businessId
        }
        let token = getToken()
        this.isCheckFlowDialogShow = true
        this.dialogTitle = data.data[data.index].desc
        this.isImgData = path + '?token=' + token + '&t=' + Math.random()
      }
    },
    // 查看时间轴
    checkTimerShaftHandle (data) {
      if (data && data.data) {
        this.uri = config.serverUrl
        let timerData = data.data[data.index]
        let isWorkflowTimer = true
        if (!timerData.procsInsId) isWorkflowTimer = false
        timerData.isWorkflowTimer = isWorkflowTimer
        this.timeLineStatus = timerData.status
        var m = this
        findEventDetail(timerData.businessId).then(resp => {
          if (resp.code && resp.code === '200') {
            m.formData = resp.data
            m.$set(m.formData, 'photoArr', m.toArray(m.formData.photo))
          }
        })
        getTaskTimer(timerData).then(resp => {
          if (resp.code && resp.code === '200') {
            this.isTimerShaftDialogShow = true
            if (resp.data.historicTaskVo && resp.data.historicTaskVo instanceof Array) {
              var data = resp.data.historicTaskVo
              for (let i = 0; i < data.length; i++) {
                const element = data[i]
                m.$set(m.activities, 'photoArr', m.toArray(m.activities.photo))
                element.photoArr = m.toArray(element.photo)
              }
              m.activities = data
              for (let i = 0; i < data.length; i++) {
                if (data[i].endTime === 0) m.status = '处理中'
                else m.status = '已完结'
              }
            }
          } else {
            this.$message({
              type: 'info',
              message: '操作失败，请联系管理员'
            })
            return ''
          }
        })
      } else {
        return ''
      }
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
        this.options = data
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.isCheckFlowDialogShow = false
      this.isTimerShaftDialogShow = false
      this.formData = {}
      this.isImgData = ''
    },
    getTableData (param) {
      getHistoricTasks(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.historicPageData = resp.data
          this.historicPageData.isCheckTimerShaftHandleInline = true
          this.historicPageData.checkPhotoTitle = '查看任务跟踪图'
          this.historicPageData.checkTimer = '查看任务流转'
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = val - 1
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      this.eventCategoryOption = getEventCategory()
      if (callbackData.btnType === 'post') {
        this.dialogTitle = '新增'
      } else {
        this.formData = callbackData.rows[0]
        let regionData = {}
        this.formData.eventCategoryArr = this.formData.eventCategory !== '' && this.formData.eventCategory !== null ? this.formData.eventCategory.split(',') : []
        regionData.id = this.formData.gridId
        regionData.items = this.options
        this.formData.gridIdArr = getAllRegion(regionData)
        this.$set(this.formData, 'photoArr', this.toArray(this.formData.photo))
      }
      this.showOnly = callbackData.sohwOnly
      this.dialogTitle = callbackData.dialogTitle
      this.dialogFormVisible = true
    },
    toArray (string) {
      let arr = []
      if (string) {
        let stringArr = string.split(',')
        for (let i = 0; i < stringArr.length; i++) {
          let obj = {}
          obj.name = 'IMG_' + i
          obj.url = stringArr[i]
          arr.push(obj)
        }
        return string.split(',')
      } else {
        return []
      }
    },
    handleCheckedRows (rows) {
      if (rows.length <= this.currentSelectedData.length && rows.length === 1) this.currentSelectedData = []
      if (rows instanceof Array && rows.length > 0) {
        findEventDetail(rows[0].businessId).then(resp => {
          if (resp.code && resp.code === '200') {
            this.currentSelectedData.push(resp.data)
            this.formData = resp.data
          } else {
            this.$message({
              type: 'info',
              message: '数据加载失败'
            })
            return ''
          }
        })
      } else {
        this.formData = {}
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.options
      this.formData.gridIdArr = getAllRegion(gridData)
      this.selectForm.gridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
<style scoped>
 .custom-dialog_style_twoLine .el-form >>> .custom-img-container .el-form-item__content {
  position: relative
}
.custom-dialog_style_twoLine .el-form >>> .custom-img-container .el-form-item__label {
  width: 25%!important
}
.custom-dialog_style_twoLine .el-form >>> .custom-img-container {
  margin-bottom: 0px
}
.custom-content-left,
.custom-img-right{
  height: 120px;
  margin-top:10px;
  overflow: hidden;
}
.custom-content-left{
  width: 73%;
  float: left;
  line-height: 200%;
  overflow: hidden;
}
.custom-content-left p:nth-child(3){
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.custom-img-right{
  width: 26%;
  float: right;
  border: 1px solid #c28d3c
}
.timeTop-right {
  text-align: center;
  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  height: 100%
}
.cardRight {
  height: auto;
  overflow: hidden;
}
.timeTop-right img {
  width: 100%;
}
.imgWapper {
  width: 189px;
  float: left;
  height: 121px;
  overflow: hidden;
  border: 1px solid #c28d3c;
  margin: 5px 5px;
  border-radius: 3px
}
</style>
